<template>
  <div>
    <complex-table
      v-loading="uiOpts.loading"
      :data="uiPods"
      @search="reloadPods"
    >
      <el-table-column :label="$t('commons.table.status')" min-width="45">
        <template #default="{ row }">
          <el-tag
            v-if="
              row.status.phase === 'Running' || row.status.phase === 'Succeeded'
            "
            type="success"
            size="small"
          >
            {{ row.status.phase }}
          </el-tag>
          <el-tag
            v-if="
              row.status.phase !== 'Running' && row.status.phase !== 'Succeeded'
            "
            type="warning"
            size="small"
          >
            {{ row.status.phase }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.name')"
        prop="name"
        min-width="80"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span class="span-link" @click="openDetail(row)">{{
            row.metadata.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.namespace.namespace')"
        min-width="40"
        prop="metadata.namespace"
        show-overflow-tooltip
      />
      <el-table-column
        :label="'CPU ' + $t('business.workload.reservation')"
        min-width="45"
      >
        <template #default="{ row }">
          {{ row.cpuRequest }}
        </template>
      </el-table-column>
      <el-table-column
        :label="'CPU ' + $t('business.workload.limit')"
        min-width="45"
      >
        <template #default="{ row }">
          {{ row.cpuLimit }}
        </template>
      </el-table-column>
      <el-table-column
        :label="
          $t('business.workload.memory') + $t('business.workload.reservation')
        "
        min-width="50"
      >
        <template #default="{ row }">
          {{ row.memoryRequest }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.workload.memory') + $t('business.workload.limit')"
        min-width="45"
      >
        <template #default="{ row }">
          {{ row.memoryLimit }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.created_time')"
        min-width="40"
        prop="metadata.creationTimestamp"
        show-overflow-tooltip
        fix
      >
        <template #default="{ row }">
          {{ row.metadata.creationTimestamp }}
        </template>
      </el-table-column>
      <ko-table-operations
        :buttons="buttons"
        :label="$t('commons.table.action')"
      />
    </complex-table>

    <el-dialog
      v-model="uiOpts.evictionDialogVisible"
      :title="'Pod ' + $t('business.pod.eviction')"
      width="30%"
    >
      <div style="margin-left: 50px">
        <p>{{ $t("business.pod.eviction_confirm") }}</p>
        <ul>
          {{
            $t("business.pod.eviction_help1")
          }}
        </ul>
        <ul>
          {{
            $t("business.pod.eviction_help2")
          }}
        </ul>
        <ul>
          {{
            $t("business.pod.eviction_help3")
          }}
        </ul>
      </div>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button size="small" @click="uiOpts.evictionDialogVisible = false">
            {{ $t("commons.button.cancel") }}
          </el-button>
          <el-button size="small" @click="onHandleSubmitEviction">{{
            $t("commons.button.confirm")
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import KoTableOperations from "@/views/domain/kubeHud/views/components/ko-table-operations/index.vue";
import { Eviction, Pod, useK8SApi } from "../../../api/k8s";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { onMounted, reactive, ref, watch } from "vue";
import { checkPermissions } from "../../../utils/permission";
import { cpuUnitConvert, memoryUnitConvert } from "../../../utils/unitConvert";
// import { listPodsWithNsSelector, evictionPod } from "@/api/pods";
// import { cordonNode } from "@/api/nodes";
// import { checkPermissions } from "@/utils/permission";
// import { cpuUnitConvert, memoryUnitConvert } from "@/utils/unitConvert";

const { nodeRepo, podRepo } = useK8SApi();
const { t } = useI18n();
const router = useRouter();

type Prop = {
  cluster?: string;
  namespace?: string;
  selector?: string;
  fieldSelector?: string;
  allocatable?: any;
  pods?: Pod[];
};

const props = withDefaults(defineProps<Prop>(), {
  cluster: "",
  namespace: "",
  selector: "",
  fieldSelector: "",
  allocatable: {}
});

const uiOpts = reactive({
  loading: false,
  evictionDialogVisible: false,
  evictionPod: {} as Pod,
  pageNum: 1,
  pageSize: 10,
  total: 0
});

const uiPods = ref<Pod & Record<string, any>[]>(props.pods ?? []);

const buttons = [
  {
    label: t("commons.button.terminal"),
    icon: "iconfont iconline-terminalzhongduan",
    click: row => {
      openTerminal(row);
    }
  },
  {
    label: t("commons.button.logs"),
    icon: "el-icon-tickets",
    click: row => {
      openTerminalLogs(row);
    }
  },
  {
    label: t("business.node.drain"),
    icon: "el-icon-delete",
    click: row => {
      openEviction(row);
    }
  }
];

const reloadPods = async (resetPage?: boolean) => {
  uiOpts.loading = true;
  uiOpts.pageNum = 1;

  // if (
  //   !checkPermissions({
  //     scope: "namespace",
  //     apiGroup: "",
  //     resource: "pods",
  //     verb: "list"
  //   })
  // ) {
  //   uiOpts.loading = false;
  //   return;
  // }

  const { ok, items } = await podRepo.getPodList({
    cluster: props.cluster,
    namespace: props.namespace,
    query: {
      labelSelector: props.selector,
      fieldSelector: props.fieldSelector
    }
  });

  if (!ok) {
    return;
  }
  uiPods.value = Object.assign([], items);
  mergePodsMetric();
};

const mergePodsMetric = () => {
  uiPods.value.forEach(item => {
    let cpuLimit = 0;
    let cpuRequest = 0;
    let memoryLimit = 0;
    let memoryRequest = 0;
    item.spec?.containers?.forEach(container => {
      if (container.resources?.limits?.cpu) {
        cpuLimit += cpuUnitConvert(container.resources.limits.cpu);
      }
      if (container.resources?.requests?.cpu) {
        cpuRequest += cpuUnitConvert(container.resources.requests.cpu);
      }
      if (container.resources?.limits?.memory) {
        memoryLimit += memoryUnitConvert(container.resources.limits.memory);
      }
      if (container.resources?.requests?.memory) {
        memoryRequest += memoryUnitConvert(container.resources.requests.memory);
      }
    });

    item.cpuLimit = cpuLimit;
    item.cpuRequest = cpuRequest;
    item.memoryLimit = memoryLimit;
    item.memoryRequest = memoryRequest;
  });

  uiOpts.loading = false;
};

const openDetail = (row: Pod) => {
  router.push({
    name: "PodDetail",
    params: { namespace: row.metadata.namespace, name: row.metadata.name },
    query: { yamlShow: "false" }
  });
};

const openEviction = (row: Pod) => {
  uiOpts.evictionDialogVisible = true;
  uiOpts.evictionPod = row;
};

const onHandleSubmitEviction = async () => {
  const res = await nodeRepo.cordonNode(
    {
      cluster: props.cluster,
      srcName: uiOpts.evictionPod.spec.nodeName
    },
    { spec: { unschedulable: true } }
  );

  if (!res.ok) {
    return;
  }

  const targetPod: Eviction = {
    apiVersion: "policy/v1beta1",
    kind: "Eviction",
    metadata: {
      name: uiOpts.evictionPod.metadata.name,
      namespace: uiOpts.evictionPod.metadata.namespace
    }
  };

  await podRepo.evictionPod(
    {
      metadata: {
        namespace: props.namespace,
        name: uiOpts.evictionPod.metadata.name
      }
    }
    // targetPod
  );

  uiOpts.evictionDialogVisible = false;
};

const openTerminal = (row: Pod) => {
  const routeUrl = router.resolve({
    path: "/terminal",
    query: {
      cluster: props.cluster,
      namespace: props.namespace,
      pod: row.metadata.name,
      container:
        row.spec.containers && row.spec.containers.length > 0
          ? row.spec.containers[0].name
          : "",
      type: "terminal"
    }
  });

  window.open(routeUrl.href, "_blank");
};

const openTerminalLogs = (row: Pod) => {
  const routeUrl = router.resolve({
    path: "/terminal",
    query: {
      cluster: props.cluster,
      namespace: props.namespace,
      pod: row.metadata.name,
      container:
        row.spec.containers && row.spec.containers.length > 0
          ? row.spec.containers[0].name
          : "",
      type: "log"
    }
  });

  window.open(routeUrl.href, "_blank");
};

watch(
  () => props.fieldSelector,
  (nv, ov) => {
    if (nv !== ov) {
      reloadPods();
    }
  }
);

watch(
  () => props.selector,
  (nv, ov) => {
    if (nv !== ov) {
      reloadPods();
    }
  }
);

watch(
  () => props.pods,
  (nv, ov) => {
    if (nv !== ov) {
      uiPods.value = nv;
      mergePodsMetric();
    }
  }
);

onMounted(() => {
  if (!props.pods || props.pods.length === 0) {
    reloadPods();
  } else {
    mergePodsMetric();
  }
});
</script>

<style scoped>
.btnSize {
  width: 28px;
  height: 28px;
}
</style>
